/*
 * Copyright (c) 2006-2019, RT-Thread Development Team
 *
 * SPDX-License-Identifier: Apache-2.0
 *
 * Change Logs:
 * Date           Author       Notes
 * 2021-05-24                  the first version
 */

#include "BspHelper.h"
#include "DeviceDef.h"
#include "LedBoardModule.h"
#include "SimpleCompletion.h"
#include <rthw.h>
#include <rtthread.h>

#if defined(RT_USING_USER_MAIN) && defined(RT_USING_HEAP)
/*
 * Please modify RT_HEAP_SIZE if you enable RT_USING_HEAP
 * the RT_HEAP_SIZE max value = (sram size - ZI size), 1024 means 1024 bytes
 */
#define RT_HEAP_SIZE (15 * 1024)
static rt_uint8_t rt_heap[RT_HEAP_SIZE];

RT_WEAK void *rt_heap_begin_get(void) {
  return rt_heap;
}

RT_WEAK void *rt_heap_end_get(void) {
  return rt_heap + RT_HEAP_SIZE;
}
#endif

// 这个函数被临时移动到ClkInitHelper中，跟随SysTick_Handler一起使用。此tick时钟中断函数也在这个文件中被定义
//void rt_os_tick_callback(void)
//{
//    rt_interrupt_enter();
//
//    rt_tick_increase();

//    rt_interrupt_leave();
//}

/**
 * This function will initial your board.
 */
void rt_hw_board_init(void) {
  //#error "TODO 1: OS Tick Configuration."
  /* 
     * TODO 1: OS Tick Configuration
     * Enable the hardware timer and call the rt_os_tick_callback function
     * periodically with the frequency RT_TICK_PER_SECOND. 
     */

  led_status.led_undefined = 0;
  led_status.led_run = 1;
  led_status.led_error = 0;
  led_status.led_busy = 0;

  /* Call components board initial (use INIT_BOARD_EXPORT()) */
  Bsp_Init();

  rt_mq_init(&debug_usart_mq,
             "debug_usart_msg",
             &debug_usart_msg_pool[0], /* 内存池指向 msg_pool */
             256,                      /* 每个消息的大小是 1 字节 */
             8192,                     /* 内存池的大小是 msg_pool 的大小 */
             RT_IPC_FLAG_PRIO);        /* 如果有多个线程等待，优先级大小的方法分配消息 */
  SWDT_FeedDog();

  // 读取系统复位状态
  {
    rt_kprintf("rmu reg: 0x%08X\n", CM_RMU->RSTF0);
    if (SET == RMU_GetStatus(RMU_FLAG_SW)) {
      rt_kprintf("reset by flasg sw\n");
    } else if (SET == RMU_GetStatus(RMU_FLAG_SWDT)) {
      rt_kprintf("reset by wdg\n");
      rt_kprintf("看门狗重启\n");
    }
  }
  /* Clear reset cause */
  LL_PERIPH_WE(LL_PERIPH_PWC_CLK_RMU);
  RMU_ClearStatus();
  LL_PERIPH_WP(LL_PERIPH_PWC_CLK_RMU);
  // 读取系统复位状态


  rt_kprintf("init board successful!");


#ifdef RT_USING_COMPONENTS_INIT
  rt_components_board_init();
#endif

#if defined(RT_USING_USER_MAIN) && defined(RT_USING_HEAP)
  rt_system_heap_init(rt_heap_begin_get(), rt_heap_end_get());
#endif
}

#ifdef RT_USING_CONSOLE

void rt_hw_console_output(const char *str) {
  //#error "TODO 3: Output the string 'str' through the uart."

  //rt_enter_critical();
  {// 消息队列方式发送
    led_busy_times = 4;
    rt_mq_send_wait(&debug_usart_mq, str, sizeof(debug_usart_tx_buf), 500);
    led_status.led_run = 1;
    //completion_done(led_work_status_sem);
  }// 消息队列方式发送
  //rt_exit_critical();
}

void rt_hw_us_delay(rt_uint32_t us) {
  DDL_DelayUS(us);
}

#endif
